/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.TX.CustomerIOTRPortal;

import java.text.ParseException;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import java.util.List;
import java.util.Calendar;
import session.TX.*;
import Helper.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Properties;
import javax.ejb.EJB;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Chen Zhe
 */
@ManagedBean (name="tableBookingMB")
@SessionScoped
public class TableBookingMB {

    /** Creates a new instance of TableBookingMB */
    public TableBookingMB() {
    }
    @EJB
    private AreaSBRemote areaBean;
    @EJB
    private OutletSBRemote outletBean;
    @EJB
    private CustomerReservationSBRemote customerReservationBean;
    private String date;
    private String areaName;
    private Long outletId;
    private String customerEmail;
    private Integer timeslot;
    private String comments;
    private Long reservationID;

    /**
     * @return the date
     */
    public String getDate() {

        return date;
    }

    /**
     * @param date the date to set
     */
    public void setDate(String date) {

        this.date = date;
        System.out.println("Date!!:" + date);
    }

    /**
     * @return the timeslots
     */
    public List<Integer> getTimeslots() throws ParseException {
        //get the day of the week g
      //  System.out.println("getTimesslots started!!!!!!!!!!!");
        List timeslots2 = new ArrayList<Integer>();
        List timeslots3 = new ArrayList<Integer>();

        int dayInt;
        String day;
        DateFormat formatter;
        Date dateConverted;
        Calendar c = Calendar.getInstance();
        if (date == null) {
        //    System.out.println("Ajax hasn't updated date!!!!!!!!!!!!!!!");
        } else {
            formatter = new SimpleDateFormat("MM/dd/yyyy");
            dateConverted = (Date) formatter.parse(date);
            c.setTime(dateConverted);
            dayInt = c.get(Calendar.DAY_OF_WEEK);
            switch (dayInt) {
                case 1:
                    day = "Sunday";
                    break;
                case 2:
                    day = "Monday";
                    break;
                case 3:
                    day = "Tuesday";
                    break;
                case 4:
                    day = "Wednesday";
                    break;
                case 5:
                    day = "Thursday";
                    break;
                case 6:
                    day = "Friday";
                    break;
                case 7:
                    day = "Saturday";
                    break;
                default:
                    day = "Monday";
            }
       //     System.out.println("the day of the week is!!!" + day);
      //      System.out.println("the outlet id is!!!!" + getOutletId());

            List areaList = getAreaBean().getAllAreas(getOutletId());

            timeslots2 = getAreaBean().retrieveTime(getAreaBean().getAreaByAreaName(areaList, areaName).getTimeslots());

        ///    System.out.println("Have already got timeslots!" + timeslots2.toString());
            if (timeslots2 == null) {
           //     System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
            }
        }
        //check for availabity, whether booking quota has exceeded the maxima quota
        for (Object o : timeslots2) {
            Integer i = (Integer) o;
            //transform the timeslot and date to a single Calendar timeslot
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
            Calendar ca = Calendar.getInstance();
            Date processDate = df.parse(date);
            ca.setTime(processDate);
            //check if the selected date satisfy the lead time and booking window 
            Calendar beforeDate = getCalendar(getEndDate());
            Calendar afterDate = getCalendar(getStartDate());
            if (ca.before(afterDate) || ca.after(beforeDate)) {
                List<Integer> timeslots = new ArrayList<Integer>();
                return timeslots;
            }
           // Integer Hour = new Integer(i.toString().substring(0, 2));
           // Integer Minute = new Integer(i.toString().substring(2, 4));
           // ca.set(Calendar.HOUR_OF_DAY, Hour);

           // ca.set(Calendar.MINUTE, Minute);
          //  System.out.println("The calendar we get from checking quota process is" + ca.getTime().toString());
            Boolean available = customerReservationBean.checkQuota(customerEmail, getOutletId(), ca, areaName, i);
       //     System.out.println("The timeslot for " + i.toString() + " is " + available);
            if (available) {
         //        System.out.println("Have already got timeslots3!" + timeslots3.toString());
                timeslots3.add(i);
            }
        }

        List timeslots = new ArrayList();
        for (Object o : timeslots3) {
            Integer i = (Integer) o;
            SelectItem option = new SelectItem(i.toString(), i.toString());
            timeslots.add(option);
        }
        return timeslots;

    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    //    System.out.println("The areaName is updated!! :" + areaName);
    }

    /**
     * @return the outletName
     */
    
    /**
     * @return the customerEmail
     */
    public String getCustomerEmail() {
        return customerEmail;
    }

    /**
     * @param customerEmail the customerEmail to set
     */
    public void setCustomerEmail(String customerEmail) {
        this.customerEmail = customerEmail;
    }

    /**
     * @return the areaNames
     */
    public List<String> getAreaNames() {
        List<Helper_Area> helperAreaList = new ArrayList<Helper_Area>();
        List<String> areaNames = new ArrayList<String>();
        helperAreaList = getAreaBean().getAllHelperAreas(outletId);
       
        for (Object o : helperAreaList) {
            Helper_Area ha = (Helper_Area) o;
            areaNames.add(ha.getAreaName());
        }
        List options = new ArrayList();
        for (String s : areaNames) {
            SelectItem option = new SelectItem(s, s);
            options.add(option);
        }

        return areaNames;
    }

    /**
     * @return the outletBean
     */
    public OutletSBRemote getOutletBean() {
        return outletBean;
    }

    /**
     * @param outletBean the outletBean to set
     */
    public void setOutletBean(OutletSBRemote outletBean) {
        this.outletBean = outletBean;
    }

    /**
     * @return the timeslot
     */
    public Integer getTimeslot() {
        return timeslot;
    }

    /**
     * @param timeslot the timeslot to set
     */
    public void setTimeslot(Integer timeslot) {
        this.timeslot = timeslot;
    }

    /**
     * @return the comments
     */
    public String getComments() {
        return comments;
    }

    /**
     * @param comments the comments to set
     */
    public void setComments(String comments) {
        this.comments = comments;
    }
    // This method will book the table, and return a booking result status, pending or successful

    public String getStatus() throws ParseException {
        if (date == null) {
            String status = "Status of Current Booking: Uncompleted";
            return status;
        } else {
            String status = null;
            DateFormat formatter;
            Boolean autoConfirm = outletBean.getAutoConfirm(outletId);
       //     System.out.println("the autoConfirm value in this outlet entitiy is!! " + autoConfirm.toString());
            //convert the String date and Integer timeslot into a single Calendar object tiemslot
            Calendar processTimeslot = Calendar.getInstance();
            formatter = new SimpleDateFormat("MM/dd/yyyy");
      //      System.out.println("the date value is!!" + date);
            Date processDate = formatter.parse(date);
            processTimeslot.setTime(processDate);
            Integer Hour = new Integer(timeslot.toString().substring(0, 2));

            processTimeslot.set(Calendar.HOUR_OF_DAY, Hour.intValue());
            Integer Minute = new Integer(timeslot.toString().substring(2, 4));
            processTimeslot.set(Calendar.MINUTE, Minute.intValue());
         //   System.out.println("The final Calender object we get contains!!" + processTimeslot.getTime().toString());

            Long rID = customerReservationBean.AddUnconfirmedReservation(customerEmail, outletId, processTimeslot,timeslot, areaName, comments);
            //if auto-confirmation  then reutrn sucessfull messagey


            if (autoConfirm) {
                // send java mail
                System.out.println("Start to send email!!!");
                Properties props = new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.socketFactory.port", "465");
                props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.port", "465");

                Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("foodsage.tcube@gmail.com", "3332720twd");
                    }
                });

                try {

                    Message message = new MimeMessage(session);
                    message.setFrom(new InternetAddress("foodsage.tcube@gmail.com"));
                    message.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(customerEmail));
                    message.setSubject("FoodSage.sg Account Confirmation");
                    message.setText("Dear customer" + "," + "\n\n You booking at " + outletId + " is successfull. Your book details are the followings:\n\n"
                            + "Date and Time: " + date + "  " + timeslot.toString() + "\nArea: " + areaName + "\nComments: " + comments
                            + "\n\n Thank you for your booking through FoodSage.com. \n\n\n Sincerely \n Ceasor Chia(FoodSage administrator)");

                    Transport.send(message);

                    System.out.println("!!!!!!!!!!!!!!!Done");

                } catch (MessagingException e) {
                    throw new RuntimeException(e);
                }

                System.out.print("Email Sent to Customer");

                //set status as return message
                status = "Your book is successful. The booking information will be sent to you through email.";
            } else {
                status = "Your reservation id is " + rID + ". Your booking status is pending, please wait for the outlet manager to confirm you the status through email. "
                        + "If you want to cancel reservation, please enter your reservation ID before cancel reservation button.";
            }

            return status;
        }
    }

    public String getStartDate() {
        Calendar ca = Calendar.getInstance();
     //   System.out.println("The lead time is!!!!!!!!!!" + outletBean.getLeadTime(outletId));
        ca.add(Calendar.DATE, outletBean.getLeadTime(outletId).intValue());
        return printCalendar(ca);
    }

    public String getEndDate() {
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, (outletBean.getBookingWindow(outletId).intValue() + outletBean.getLeadTime(outletId).intValue()));
        return printCalendar(ca);
    }

    public String printCalendar(Calendar ca) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
   //     System.out.println("the calender we get here is" + sdf.format(ca.getTime()));
        return sdf.format(ca.getTime());
    }

    public Calendar getCalendar(String date) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        Date d = formatter.parse(date);
        Calendar ca = Calendar.getInstance();
        ca.setTime(d);
        return ca;
    }

    public Long getReservationID() {

        return reservationID;
    }

    public void setReservationID(Long id) {
        this.reservationID = id;
    }

    public String getCancelMessage() {
        String message;
        if (!(reservationID == null)) {
            Boolean cancelled = customerReservationBean.cancelReservation(reservationID);

            if (cancelled) {
                message = "Reservation ID :" + reservationID + " has been cancelled successfully";
            } else {
                message = "Reservation ID is invalid";
            }

        } else {
            message = "";
        }
        return message;

    }

    public String getNoShowPenalty() {
        System.out.println("It said that the outletID is!!!!!!:" + outletId);
        Double d = outletBean.getNoShowPenalty(outletId);
        String message;
        if (d == null) {
            message = "";
        } else if (d == 0) {
            message = "There will be no no-show-penalty fee.";
        } else {
            message = "The no show penalty fee is " + d.toString();
        }
        return message;
    }

    /**
     * @return the outletID
     */
    public Long getOutletId() {
        return outletId;
    }

    /**
     * @param outletID the outletID to set
     */
    public void setOutletId(Long outletID) {
        this.outletId = outletID;
    }

    /**
     * @return the areaBean
     */
    public AreaSBRemote getAreaBean() {
        return areaBean;
    }

    /**
     * @param areaBean the areaBean to set
     */
    public void setAreaBean(AreaSBRemote areaBean) {
        this.areaBean = areaBean;
    }
}
